class CacheStorage {
  constructor(store) {

    if (!store) {
      console.log('不支持localStorage')
      return
    }
    this._store = store
  }

  setItem (_k, _v) {
    if (!this._store) return
    this._store.setItem(_k, this.filterValue(_v))
  }

  getItem (_k) {
    if (!this._store) return
    let res
    res = this._store.getItem(_k)
    return JSON.parse(res)
  }

  removeItem (_k) {
    if (!this._store) return
    // eslint-disable-next-line no-unused-vars
    let res
    res = this._store.removeItem(_k)
  }

  clear () {
    if (!this._store) return
    this._store.clear()
  }

  getType (para) {
    let type = typeof para
    if (type === 'number' && isNaN(para)) return 'NaN'
    if (type !== 'object') return type
    return Object.prototype.toString
      .call(para)
      .replace(/[\[\]]/g, '') // eslint-disable-line
      .split(' ')[1]
      .toLowerCase()
  }

  filterValue (val) {
    let vType = this.getType(val)
    let nullVal = ['null', 'undefined', 'NaN']
    let stringVal = ['boolen', 'number', 'string']
    if (nullVal.indexOf(vType) >= 0) return ''
    if (stringVal.indexOf(vType) >= 0) return val
    return JSON.stringify(val)
  }
}

class SessionStorage extends CacheStorage {
  constructor(store) { // eslint-disable-line
    super(store)
  }
}



const cache = new SessionStorage(window.sessionStorage || sessionStorage)

export {
  cache
}
